# tsdangerous是flask中引用的一个第三方包，用来解决生成token等网络安全问题。
from itsdangerous import URLSafeTimedSerializer

# 以下为pyjwt相关的文档
# https://blog.csdn.net/lly1122334/article/details/126760077
# https://pyjwt.readthedocs.io/en/stable/usage.html
import jwt
import datetime

from functools import wraps
from flask import request, g
from flask_restful import Resource
from flask_shop.utils.response_message import get_response, ResponseType

jwt_key = "88313D1B-7D5E-4500-928B-FEA3FF183A27"


# 生成认证签名
def generate_auth_token(uid: str) -> str:
    # 到期时间
    exp = datetime.datetime.now(tz=datetime.timezone.utc) + datetime.timedelta(days=2)

    payload = {
        "uid": uid,
        "exp": exp
    }

    # exp (Expiration Time)：过期时间，可用 UTC 时间戳或 datetime
    # timestamp = int(datetime.datetime(2022, 1, 1).timestamp())  # 2022-01-01的时间戳，类型为int
    # after_a_week = datetime.datetime.now(tz=datetime.timezone.utc) + datetime.timedelta(days=7)  # 一周后，类型为datetime
    token = jwt.encode(payload=payload, key=jwt_key, algorithm="HS256")
    return token


def verify_auth_token(token: str) -> int:
    try:
        dict = jwt.decode(jwt=token, key=jwt_key, algorithms=["HS256"])
        return dict["uid"]
    except Exception:
        return None

def super_admin_required(func):
    """ 超级管理员：鉴权装饰器 """
    @wraps(func)
    def wrapper(*args, **kwargs):
        token = request.headers.get("token")
        if token is None:
            return get_response(ResponseType.not_login)

        user_id = verify_auth_token(token)
        if user_id:
            g.user_id = user_id
        else:
            return get_response(ResponseType.token_error)
        # 还可以继续验证接口签名
        return func(*args, **kwargs)

    return wrapper

def login_required(func):
    """ 鉴权装饰器 """

    @wraps(func)
    def wrapper(*args, **kwargs):
        token = request.headers.get("token")
        print(request)
        test = request
        if token is None:
            return get_response(ResponseType.not_login)

        user_id = verify_auth_token(token)
        if user_id:
            g.user_id = user_id
        else:
            return get_response(ResponseType.token_error)
        # 还可以继续验证接口签名
        return func(*args, **kwargs)

    return wrapper


if __name__ == '__main__':
    print(generate_auth_token("920315"))
    print(generate_auth_token("920315"))
    token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiI5MjAzMTUiLCJleHAiOjE2OTk3OTk1MzJ9.jxk7KLjimh6I1yk3xVSLuiFIdfLyZSxUOL2KvtdMkxU"
    print(verify_auth_token(token))
